import chalk from 'chalk';
import FormData from 'form-data';
import fs from 'fs';
import path from 'path';
import { prompt, toStringify } from '../utils';
import request from '../utils/request';

async function uploadRequest(path, callback) {
  const formData = new FormData();
  formData.append('file', fs.createReadStream(path));
  formData.append('productId', 10);
  console.log(chalk.blue(`开始上传文件: ${path}`));

  try {
    const res = await request('http://pipeline.ebonex.io/api/assets/upload', {
      headers: {
        ...formData.getHeaders(),
      },
      data: formData,
      method: 'POST',
    });

    console.log(
      chalk.green(
        `文件上传成功:${toStringify({
          本地路径: path,
          cdn地址: res?.data,
        })}`,
      ),
    );
  } catch (err) {
    console.error(chalk.red(err));
  } finally {
    callback();
  }
}

function getAllFiles(dirPath, filesArray) {
  const files = fs.readdirSync(dirPath);

  files.forEach((file) => {
    if (!['.DS_Store', '.git', '.vscode'].includes(path.normalize(file))) {
      const filePath = path.join(dirPath, file);
      const stat = fs.statSync(filePath);

      if (stat.isDirectory()) {
        getAllFiles(filePath, filesArray); // 递归遍历文件夹
      } else {
        filesArray.push(filePath); // 将文件路径添加到数组中
      }
    }
  });

  return filesArray;
}

function getAllFilesHandle(dirPath) {
  const filesArray = [];

  console.log(chalk.blue('Loading...')); // 使用chalk添加颜色和样式打印加载信息

  getAllFiles(dirPath, filesArray);

  console.log(chalk.green('Loading complete.')); // 使用chalk添加颜色和样式打印加载完成信息

  return filesArray;
}

function uploadFiles(filesArray) {
  let count = 0;
  const parallelList = [...filesArray];
  const pool = () => {
    while (count < 5 && parallelList.length > 0) {
      const filePath = parallelList.shift();
      uploadRequest(filePath, () => {
        count--;
        pool();
      });
      count++;
    }
  };
  pool();
}

export default async function upload(
  path?: string,
  fileList?: string | Array<string>,
): Promise<void> {
  const currentDir = path || process.cwd(); // 获取当前目录
  let files = [];
  if (typeof fileList === 'string') {
    files = [fileList];
  } else {
    files = getAllFilesHandle(currentDir);
  }
  if (files?.length > 10) {
    console.log(chalk.green(`上传文件列表：${toStringify(files)}`));
    const result = await prompt([
      {
        type: 'confirm',
        name: 'flag',
        message: '是否确认上传?',
      },
    ]);
    if (!result?.flag) {
      return;
    }
  }
  await uploadFiles(files);
}
